﻿using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DbType = System.Data.DbType;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创 建：超级管理员
    /// 日 期：2022-03-07 13:45
    /// 描 述：工程数据图元
    /// </summary>
    public class ec_enginedata_pixelService
    {
        #region 仓储
        Repository<ec_projectEntity> _projectRepository => new Repository<ec_projectEntity>();
        Repository<ec_enginedata_pixelEntity> _enginedataPixelRepository => new Repository<ec_enginedata_pixelEntity>();
        #endregion
        #region 获取数据
        /// <summary>
        /// 清理无效的pixel（句柄对应的文件、位号不存在时）
        /// </summary>
        /// <param name="drawingFileId"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public bool Clear(string drawingFileId, string projectId)
        {
            if (string.IsNullOrEmpty(projectId))
            {
                return true;
            }
            else
            {
                var ProjectEntity = _projectRepository.GetById(projectId);
                var strSql = $@"select t3.EngineDataID tagnumber,t2.DrawingFileID DrawingFileName,t1.*
FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} t1 
LEFT JOIN ec_drawing_file_{ProjectEntity.ProjectIndex} t2 ON t2.DrawingFileID = t1.DrawingFileID 
left JOIN ec_enginedata_{ProjectEntity.ProjectIndex} t3 ON t3.EngineDataID = t1.EngineDataID ";

                //var pixels = this.BaseRepository().FindList<ec_enginedata_pixelEntity>(strSql, new object());
                var pixels = SqlSugarHelper.Db.SqlQueryable<ec_enginedata_pixelEntity>(strSql.ToString()).ToList();
                foreach (var pixel in pixels)
                {
                    if (string.IsNullOrEmpty(pixel.EngineDataID) || string.IsNullOrEmpty(pixel.DrawingFileID) || string.IsNullOrEmpty(pixel.PixelCode))
                    {
                        SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE  EngineDataPixelID = @EngineDataPixelID  ",
                            new { EngineDataPixelID = pixel.EngineDataPixelID });
                        continue;
                    }

                    if (string.IsNullOrEmpty(pixel.TagNumber) || string.IsNullOrEmpty(pixel.DrawingFileName))
                    {
                        SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE  EngineDataPixelID = @EngineDataPixelID  ",
                           new { EngineDataPixelID = pixel.EngineDataPixelID });
                        continue;
                    }
                }
            }


            return true;
        }
        /// <summary>
        /// 获取列表数据(目前是不会包括OPC的数据的，因为OPC不会在表<see cref="ec_enginedataEntity"/>里有东西)
        /// <summary>
        /// <param name="NeedDeleted">是否需要查询出被删的</param>
        /// <returns></returns>
        public IEnumerable<ec_enginedata_pixelEntity> GetList(string queryJson, bool NeedDeleted = false)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(" SELECT t1.*,t2.DrawingFileName,t3.tagnumber,t4.ObjectTypeName ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    strSql.Append(@" FROM ec_enginedata_pixel t1 
                            JOIN ec_drawing_file t2 ON t2.DrawingFileID = t1.DrawingFileID ");
                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    var ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($@"  FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} t1 
                            JOIN ec_drawing_file_{ProjectEntity.ProjectIndex} t2 ON t2.DrawingFileID = t1.DrawingFileID 
                            JOIN ec_enginedata_{ProjectEntity.ProjectIndex} t3 ON t3.EngineDataID = t1.EngineDataID
                            LEFT JOIN ec_objecttype_{ProjectEntity.ProjectIndex} t4 ON t3.ObjectTypeID = t4.ObjectTypeID");
                }
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["DrawingFileID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("DrawingFileID", queryParam["DrawingFileID"].ToString(), DbType.String));
                    strSql.Append(" AND t1.DrawingFileID = @DrawingFileID  ");
                }
                if (!queryParam["PixelCode"].IsEmpty())
                {
                    dp.Add(new SugarParameter("PixelCode", queryParam["PixelCode"].ToString(), DbType.String));
                    strSql.Append(" AND t1.PixelCode = @PixelCode  ");
                }
                if (!queryParam["EngineDataID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("EngineDataID", queryParam["EngineDataID"].ToString(), DbType.String));
                    strSql.Append(" AND t1.EngineDataID = @EngineDataID  ");
                }
                //return this.BaseRepository().FindList<ec_enginedata_pixelEntity>(strSql.ToString(), dp);
                var res = SqlSugarHelper.Db.SqlQueryable<ec_enginedata_pixelEntity>(strSql.ToString()).AddParameters(dp).ToList();
                if (NeedDeleted)
                {
                    //需要被删的部分
                    return res;
                }
                else
                {
                    //仅返回没删的
                    return res.Where(x => x.DeleteFlg != 1);
                }

            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 获取图纸工程数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_enginedata_pixelEntity> GetDrawingEnginePixel(string queryJson)
        {
            try
            {
                var queryParam = queryJson.ToJObject();
                var strSql = new StringBuilder();
                strSql.Append(" SELECT t1.*,t2.DrawingFileName,t3.TagNumber,t3.ObjectTypeID,t4.ObjectTypeName ");
                if (queryParam["ProjectId"].IsEmpty())
                {
                    strSql.Append(@" FROM ec_enginedata_pixel t1
                            LEFT JOIN ec_drawing_file t2 ON t2.DrawingFileID = t1.DrawingFileID
                            LEFT JOIN ec_enginedata t3 ON t3.EngineDataID = t1.EngineDataID
                            LEFT JOIN ec_objecttype t4 ON t4.ObjectTypeID = t3.ObjectTypeID");
                }
                else
                {
                    //var ProjectEntity = this.BaseRepository().FindEntity<ec_projectEntity>(queryParam["ProjectId"].ToString());
                    var ProjectEntity = _projectRepository.GetById(queryParam["ProjectId"].ToString());
                    strSql.Append($@" FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} t1
                            LEFT JOIN ec_drawing_file_{ProjectEntity.ProjectIndex} t2 ON t2.DrawingFileID = t1.DrawingFileID
                            LEFT JOIN ec_enginedata_{ProjectEntity.ProjectIndex} t3 ON t3.EngineDataID = t1.EngineDataID
                            LEFT JOIN ec_objecttype_{ProjectEntity.ProjectIndex} t4 ON t4.ObjectTypeID = t3.ObjectTypeID");
                }
                strSql.Append(" WHERE 1=1 ");
                // 虚拟参数
                //var dp = new DynamicParameters(new { });
                var dp = new List<SugarParameter>();
                if (!queryParam["DrawingFileID"].IsEmpty())
                {
                    if (queryParam["DrawingFileID"].ToString() != "0")   //等于0 也相当于忽略
                    {
                        dp.Add(new SugarParameter("DrawingFileID", queryParam["DrawingFileID"].ToString(), DbType.String));
                        strSql.Append(" AND t1.DrawingFileID = @DrawingFileID ");
                    }
                }
                if (!queryParam["DrawingCatalogueID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("DrawingCatalogueID", queryParam["DrawingCatalogueID"].ToString(), DbType.String));
                    strSql.Append(" AND t2.DrawingCatalogueID = @DrawingCatalogueID ");
                }
                if (!queryParam["ObjectTypeID"].IsEmpty())
                {
                    dp.Add(new SugarParameter("ObjectTypeID", queryParam["ObjectTypeID"].ToString(), DbType.String));
                    strSql.Append(" AND t3.ObjectTypeID = @ObjectTypeID ");
                }
                //return this.BaseRepository().FindList<ec_enginedata_pixelEntity>(strSql.ToString(), dp);
                var res = SqlSugarHelper.Db.SqlQueryable<ec_enginedata_pixelEntity>(strSql.ToString()).AddParameters(dp).ToList();
                return res.Where(x => x.DeleteFlg != 1);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        /// <summary>
        /// 获取工程数据图元表数据
        /// <summary>
        /// <param name="EngineDataID">工程数据ID</param>
        /// <param name="ProjectId">项目ID</param>
        /// <returns></returns>
        public IEnumerable<ec_enginedata_pixelEntity> GetEnginePixelById(string ProjectId, string EngineDataID)
        {
            try
            {
                var strSql = new StringBuilder();
                strSql.Append(@" SELECT t2.* ");
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    strSql.Append($@" FROM ec_drawing_file t1
                           join ec_enginedata_pixel t2 on t1.DrawingFileID=t2.DrawingFileID
                           WHERE t2.EngineDataID = '{EngineDataID}' ");
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    strSql.Append($@" FROM ec_drawing_file_{ProjectEntity.ProjectIndex} t1
                           join ec_enginedata_pixel_{ProjectEntity.ProjectIndex} t2 on t1.DrawingFileID=t2.DrawingFileID 
                           WHERE t2.EngineDataID = '{EngineDataID}' ");
                }
                //return this.BaseRepository().FindList<ec_enginedata_pixelEntity>(strSql.ToString());
                var res = SqlSugarHelper.Db.SqlQueryable<ec_enginedata_pixelEntity>(strSql.ToString()).ToList();
                return res.Where(x => x.DeleteFlg != 1);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 保存工程数据图元表数据
        /// <param name="engineDataID">工程数据ID</param>
        /// <param name="entityList">pixelCode的集合</param>
        /// <summary>
        /// <returns></returns>
        public void SavePixelBatch(string engineDataID, ec_enginedata_pixelEntity entity, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {

                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    if (entity.EngineDataPixelID == "")
                    {
                        entity.Create(); // 创建一个主键
                        //db.InsertByNoMap(entity, $"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}");
                        _enginedataPixelRepository.AsInsertable(entity).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }
                    else
                    {
                        entity.Modify(entity.EngineDataPixelID); // 包括修改主键
                        //db.UpdateByNoMap(entity, $"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}", "EngineDataPixelID");
                        _enginedataPixelRepository.AsInsertable(entity).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                    }




                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 保存工程数据图元表数据（新增），web
        /// <param name="engineDataID">工程数据ID</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEnginePixel(string engineDataID, List<ec_enginedata_pixelEntity> entityList, string ProjectId)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                    _enginedataPixelRepository.Delete(t => t.EngineDataID == engineDataID);
                    _enginedataPixelRepository.InsertRange(entityList);
                }
                else
                {
                    var ProjectEntity = _projectRepository.GetById(ProjectId);
                    SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE EngineDataID = '{engineDataID}' ");
                    //db.InsertByNoMap(entityList, $"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}");
                    _enginedataPixelRepository.AsInsertable(entityList).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                }
                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }


        /// <summary>
        /// 批量保存工程数据图元（客户端检入时）
        /// </summary>
        /// <param name="CheckedEntityList">图上来的句柄信息</param>
        /// <param name="ProjectId"></param>
        /// <param name="drawingFileID"></param>
        public void SavePixels(List<ec_enginedata_pixelEntity> CheckedEntityList, string ProjectId, string drawingFileID)
        {
            SqlSugarHelper.Db.BeginTran();
            try
            {
                //获取某个图纸上的图元数据
                var existPixels = this.GetList("{\"ProjectId\":\"" + ProjectId + "\",\"DrawingFileID\":\"" + drawingFileID + "\"}", true).ToList();
                ec_projectEntity ProjectEntity = new ec_projectEntity();
                if (!string.IsNullOrWhiteSpace(ProjectId))
                {
                    ProjectEntity = _projectRepository.GetById(ProjectId);
                }
                foreach (var it in existPixels)
                {
                    //pixel的新建是在对象提交时就搞定了（UpdatePixelAndPropBatch，删除 再 插入）
                    if (!CheckedEntityList.Exists(p => p.PixelCode == it.PixelCode))//如果提交的pixel在数据库里没有，就准备删
                    {
                        if (string.IsNullOrWhiteSpace(ProjectId))
                        {
                            //_enginedataPixelRepository.Delete(t => t.EngineDataPixelID == it.EngineDataPixelID);
                        }
                        else
                        {
                            //????? 难道这个就是丢失的？留着不删会如何？
                            //比如A电脑10.5号保存检入了，另外一台电脑打开（但是状态是10.1号的），检入时就可能把1号~5号期间内画到图面上的东西给删掉
                            //SqlSugarHelper.Db.Ado.ExecuteCommand($" DELETE FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE EngineDataPixelID = '{it.EngineDataPixelID}'; ");
                            //2023.10.27 打个标签
                            it.DeleteFlg = 1;
                        }
                    }
                    else
                    {
                        //存在
                        it.DeleteFlg = 0;
                    }
                }
                _enginedataPixelRepository.AsUpdateable(existPixels).AS($"ec_enginedata_pixel_{ProjectEntity.ProjectIndex}").ExecuteCommand();
                if (string.IsNullOrWhiteSpace(ProjectId))
                {
                }
                else
                {
                    //db.ExecuteBySql($@"UPDATE ec_enginedata_{ ProjectEntity.ProjectIndex} T1
                    //                    SET DataStatus = '00001'
                    //                    WHERE (SELECT COUNT(*) FROM ec_enginedata_pixel_{ ProjectEntity.ProjectIndex} WHERE EngineDataID = T1.EngineDataID ) <= 0");
                    //db.ExecuteBySql($@"UPDATE ec_enginedata_{ProjectEntity.ProjectIndex} T1
                    //                    SET DataStatus = '00002'
                    //                    WHERE (SELECT COUNT(*) FROM ec_enginedata_pixel_{ProjectEntity.ProjectIndex} WHERE EngineDataID = T1.EngineDataID ) > 0 AND DataStatus != '00003'");

                    foreach (var EngineDataID in existPixels.Select(x => x.EngineDataID).Distinct())
                    {
                        if (EngineDataID != null)
                        {
                            SqlSugarHelper.Db.Ado.ExecuteCommand($@"UPDATE ec_enginedata_{ProjectEntity.ProjectIndex} T1
                                        SET DataStatus = '00002'
                                        WHERE DataStatus != '00003' and EngineDataID='{EngineDataID}'");
                        }


                    };
                }

                SqlSugarHelper.Db.CommitTran();
            }
            catch (Exception ex)
            {
                SqlSugarHelper.Db.RollbackTran();
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowServiceException(ex);
                }
            }
        }

        #endregion

    }
}
